import { Button,  message, Popconfirm, Space, Table } from "antd"
import {  useRef } from "react"
import { useRequest } from "umi"
import type { dataType } from './editForm';
import EditForm from './editForm'

interface PropsType {
  garbage_classify_id?: number
}


const GarbageBox: React.FC<PropsType> = ({garbage_classify_id}) => {
  const modelComRef: any = useRef(null);
  const { loading, data, run, params } = useRequest({
    url: garbage_classify_id ?  '/garbage/getGarbage?garbage_classify_id=' + garbage_classify_id : '/garbage/getGarbage'
  })

  const { run: delApi, loading: delLoading } = useRequest((id) => ({
    method: 'post',
    url: '/garbage/delGarbage',
    data: {id}
  }), { manual: true })

  const handleDel = async (id: string) => {
    await delApi(id)
    run(params[0])
    message.success('操作成功')
  }

  const handleFormSubmit = () => {
    run(params[0])
  }

  const columns = [
    { title: 'id', dataIndex: 'id' },
    { title: '垃圾名称', dataIndex: 'garbage_name' },
    { 
      title: '垃圾分类',
      dataIndex: 'garbage_classify_id',
      render: (text: number) => (
        <span>{['','有害垃圾','厨余垃圾','可回收物','','其他垃圾'][text]}</span>
      )
    },
    { title: '垃圾备注', dataIndex: 'garbage_desc' },
    { title: '大写索引', dataIndex: 'garbage_indexes' },
    {
      title: '操作',
      render: (text: string, record: dataType) => (
        <>
          <Space>
            <Button onClick={ () => modelComRef.current.open(2, record) } size="small" type="primary" ghost>修改</Button>
            <Popconfirm
              onConfirm={() => handleDel(record.id)}
              okButtonProps={{ loading: delLoading }}
              title="确认删除?"
            >
              <Button size="small" danger>删除</Button>
            </Popconfirm>
          </Space>
        </>
      )
    },
  ]
  if (garbage_classify_id) {
    columns.splice(2, 1)
  }

  return <>
    <div style={{ marginBottom: '8px' }}>
      <Button type="primary" onClick={ () => modelComRef.current.open(1) }>新增</Button>
    </div>
    <Table loading={loading} columns={columns} dataSource={data} rowKey="id" />
    <EditForm garbage_classify_id={garbage_classify_id} submit={handleFormSubmit} cRef={modelComRef} />
  </>
}

export default GarbageBox